<template>
  <Dialog v-model="dialogVisible" :title="`${dialogTitle}权重设置`" width="1400px">
    <div class="matix">
      <el-form ref="formRef" :model="state">
        <el-table :data="state.tableData" border size="large" class="filed_table">
          <!-- <span v-if="$index <= index">{{ row[item.key] }}</span> -->
          <el-table-column prop="key" label="横向比纵向" align="center" />
          <template v-for="(item, index) in state.tableData" :key="item.key">
            <el-table-column :prop="item.key" :label="item.key" align="center">
              <template #default="scoped">
                <span v-if="scoped.$index <= index"> \ </span>
                <span v-else>
                  <el-form-item required :prop="`tableData[${scoped.$index}][${item.key}]`">
                    <el-select v-model="scoped.row[item.key]" placeholder="请选择">
                      <template v-for="option in options" :key="option.value">
                        <el-option :label="option.label" :value="option.value" />
                      </template>
                    </el-select>
                  </el-form-item>
                </span>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </el-form>
    </div>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submit">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { getSingleWeight, updataWeight, updataSingleWeight } from '@/api/appraisal/index'
import { ElMessageBox } from 'element-plus'
import { ahpWeight, consistencyCheck, type Matrix } from '@/utils/aphWeight'

const options = [
  { label: '前者与后者同样重要', value: '1' },
  { label: '介于(前者比后者同样重要和稍微重要)', value: '2' },
  { label: '前者比后者稍微重要', value: '3' },
  { label: '介于(前者比后者稍微重要和明显重要)', value: '4' },
  { label: '前者比后者明显重要', value: '5' },
  { label: '介于(前者比后者明显重要和强烈重要)', value: '6' },
  { label: '前者比后者强烈重要', value: '7' },
  { label: '介于(前者比后者强烈重要和极端重要)', value: '8' },
  { label: '前者比后者极端重要', value: '9' },
  { label: '介于(后者比前者同样重要和稍微重要)', value: '1/2' },
  { label: '后者比前者稍微重要', value: '1/3' },
  { label: '介于(后者比前者稍微重要和明显重要)', value: '1/4' },
  { label: '后者比前者明显重要', value: '1/5' },
  { label: '介于(后者比前者明显重要和强烈重要)', value: '1/6' },
  { label: '后者比前者强烈重要', value: '1/7' },
  { label: '介于(后者比前者强烈重要和极端重要)', value: '1/8' },
  { label: '后者比前者极端重要', value: '1/9' }
]

const message = useMessage()

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const weightId = ref()
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const formRef = ref()
const state = reactive<any>({
  tableData: []
})

const open = (id: number, title: string) => {
  dialogVisible.value = true
  dialogTitle.value = title
  weightId.value = id
  createTable()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const createTable = async () => {
  const data = await getSingleWeight(weightId.value)
  state.tableData = data.map((item) => {
    return {
      ...item,
      keyId: Number(item.keyId)
    }
  })
}

// 自动填充值
const autoFillValue = () => {
  state.tableData.forEach((item: any, index: number) => {
    for (let i = index; i < state.tableData.length; i++) {
      const row = state.tableData[i]
      if (i === index) {
        item[row['key']] = '1'
      } else {
        const str = row[item.key]
        if (isFraction(str)) {
          const [_numerator, denominator] = str.split('/')
          item[row['key']] = denominator.toString()
        } else {
          item[row['key']] = `1/${row[item.key]}`
        }
      }
    }
  })
}

// 生成矩阵
const getMartrix = (data: any): Matrix => {
  const martrix: any[] = []
  for (let i = 0; i < data.length; i++) {
    const item = data[i]
    const row: any = []
    for (let j = 0; j < data.length; j++) {
      const col = data[j]
      row.push(transformNumber(item[col['key']]))
    }
    martrix.push(row)
  }
  return martrix
}

// 是否是分数字符串
const isFraction = (str: string): boolean => {
  const reg = /^-?\d+\/\d+$/
  return reg.test(str)
}

// 转数字
const transformNumber = (str: string) => {
  if (isFraction(str)) {
    const [numerator, denominator] = str.split('/')
    return parseInt(numerator, 10) / parseInt(denominator, 10)
  } else {
    return Number(str)
  }
}

const emit = defineEmits(['success'])
const submit = () => {
  formLoading.value = true
  return new Promise(async (resolve, reject) => {
    try {
      await formRef.value.validate()
      autoFillValue()
      const matrix = getMartrix(state.tableData)
      console.log('矩阵', matrix)

      // 计算权重
      const criteriaWeights = ahpWeight(matrix)
      console.log('权重', criteriaWeights)

      // 一致性检验
      const { CR, result } = consistencyCheck(matrix, criteriaWeights)
      // console.log(state.title, CR);
      console.log('一致性检验', CR)

      if (result) {
        const weightColumns = state.tableData.map((item, index) => {
          return {
            id: item.keyId,
            pid: weightId.value,
            name: item.key,
            dataId: 0,
            value: Number(criteriaWeights[index].toFixed(2))
          }
        })
        console.log('weightColumns', weightColumns)

        await updataSingleWeight(weightId.value, state.tableData)
        await updataWeight(weightColumns)

        emit('success', { pid: weightId.value, list: weightColumns })
        //   resolve(toRaw(state.tableData))
        message.success('矩阵一致性检验通过')
        dialogVisible.value = false
      } else {
        ElMessageBox.alert(`${dialogTitle.value} 矩阵不具有一致性，需要调整`, '', {
          confirmButtonText: '确定',
          type: 'error'
        })
        // reject(`${state.title} 二级权重矩阵不具有一致性，需要调整`)
      }
      formLoading.value = false
    } catch (error) {
      formLoading.value = false
      reject(error)
    }
  })
}
</script>

<style lang="scss" scoped>
.el-form-item--large {
  margin-bottom: 0;
}
</style>
